package com.example.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public final class DataBuilder {

	private static Gson gson = new Gson();
	
	public static<T> String buildJson(T data){
		return gson.toJson(data);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T buildObject(String data, T t) throws Exception {
		GsonBuilder gsonb = new GsonBuilder();
		Gson gson = gsonb.create();
		T result = (T) gson.fromJson(data, t.getClass());
		return result;
	}
	
	public static <T> T buildObject(String data, Class<T> type) throws Exception {
		GsonBuilder gsonb = new GsonBuilder();
		Gson gson = gsonb.create();
		T result = (T) gson.fromJson(data, type);
		return result;
	}
	
	public static String buildRandomMacAddress(){
		String macid = "";
		
		String text = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
//		text = StringUtils.substring(text, 0, 12);
		List<String> parts = new ArrayList<>();
		
		for(int i = 0; i < 12; i += 2){
			parts.add(text.substring(i, i + 2));
		}
		
		macid = StringUtils.join(parts, ":");
		
		return macid.toUpperCase();
	}
	
	/**
	 * 查找本机mac地址
	 * @return 第一个mac地址
	 * @throws Exception
	 */
	public static String buildLocalMacAddress() throws Exception {
		List<String> list = buildLocalAllMacAddress();
		
		String mac = null;
		for (String m : list) {
			if (!m.startsWith("0")) {
				mac = m;
				break;
			}
		}
		
		return mac;   
	}
	
	/**
	 * 查找本机mac地址
	 * @return
	 * @throws Exception
	 */
	public static List<String> buildLocalAllMacAddress() throws Exception {
		List<String> list = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> e = NetworkInterface
					.getNetworkInterfaces();// 返回所有网络接口的一个枚举实例
			while (e.hasMoreElements()) {
				NetworkInterface network = e.nextElement();// 获得当前网络接口
				if (network != null) {
					if (network.getHardwareAddress() != null) {
						// 获得MAC地址
						// 结果是一个byte数组，每项是一个byte，我们需要通过parseByte方法转换成常见的十六进制表示
						byte[] addres = network.getHardwareAddress();
						StringBuffer sb = new StringBuffer();
						if (addres != null && addres.length > 1) {
							sb.append(parseByte(addres[0])).append(":")
									.append(parseByte(addres[1])).append(":")
									.append(parseByte(addres[2])).append(":")
									.append(parseByte(addres[3])).append(":")
									.append(parseByte(addres[4])).append(":")
									.append(parseByte(addres[5]));
							list.add(sb.toString().toUpperCase());
						}
					}
				} else {
					System.out.println("获取MAC地址发生异常");
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}

		String mac = null;
		for (String m : list) {
			if (!m.startsWith("0")) {
				mac = m;
				break;
			}
		}
		return list;   
	}
	
	private static byte[] createChecksum(File file) throws Exception {  
        InputStream fis = null;  
        fis = new FileInputStream(file);  
        byte[] buffer = new byte[1024];  
        MessageDigest complete = MessageDigest.getInstance("MD5");  
        int numRead = -1;  
  
        while ((numRead = fis.read(buffer)) != -1) {  
        	complete.update(buffer, 0, numRead);  
        }
        fis.close();
        
        return complete.digest();  
    }  
  
    // see this How-to for a faster way to convert  
    // a byte array to a HEX string  
    public static String buidMD5Checksum(File file) throws Exception {  
      
            if (!file.isFile()) {  
                return null;  
            }  
            byte[] b = createChecksum(file);  
            if(null == b){  
                return null;  
            }  
            StringBuilder result = new StringBuilder();  
  
            for (int i = 0; i < b.length; i++) {  
                result.append(Integer.toString((b[i] & 0xff) + 0x100, 16)  
                        .substring(1));  
            }  
            return result.toString();  
  
    }  
    
	private static String parseByte(byte b) {
		int intValue = 0;
		if (b >= 0) {
			intValue = b;
		} else {
			intValue = 256 + b;
		}
		return Integer.toHexString(intValue);
	}
} 

